package com.dynamic.mybatis.core.toolkit;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;

/**
 * @Description
 * @Author xs
 * @Date 2023/4/17 10:25
 */
public class XmlUtil {


    public static String javaApacheFormatPretty(String xml) {
        OutputFormat format = new OutputFormat();
        format.setIndenting(true);
        format.setIndent(2);
        format.setOmitXMLDeclaration(true);
        format.setLineWidth(120);
        StringWriter writer = new StringWriter();
        XMLSerializer serializer = new XMLSerializer(writer, format);
        ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
        try {
            Document    document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bis);
            serializer.serialize(document.getDocumentElement());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                bis.close();
                writer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return  writer.toString();
    }

}